<?php

namespace app\api\model;

use app\api\controller\sales\SaleAdmin;
use app\api\service\Integral;
use app\common\services\BaseServices;
use think\Model;
use think\Db;
use think\Exception;
use app\common\model\ClaimOrder;
use app\common\logic\ProductLogic;
use app\common\logic\ActionsRecordLogic;
use app\common\logic\ShenZhenPingAnEmployerLogic;
use think\db\Query;


class Neworders extends Model
{
    private static $instance = null;

	public function __construct($data = [])
    {
        parent::__construct($data);
    }
    
    /**
     * 获得订单列表
     * type=1 保障中(保障终止日期 大于当前时间，并且保障起始日期小于当前时间，status是6和5，保障中)
     * type=2 待处理(待支付,status=1)
     * type=3 可续保(距离到期日期《30，保障期》30)
     * type=4 已失效(保障终止日期 小于当前时间，并且status是6   显示过保)
     * type=5 待生效
     * type=8 已取消
     * type=9 订单未添加完的
     */
    public function getOrders($data)
    {
        $where['uid'] = $data['uid'];
        
        $today = time();        
        $result = array();
        
        if($data['type'] == 1){
            $where = [
                'uid' => $data['uid'],
                'status' => ['in', [5, 6]],
                'e_time' => ['gt', datetime(time(), 'Y-m-d') . ' 23:59:59'],
            ];
            $result = Db::name('order')->where($where)->field('policy_money,applicant_name,s_time,e_time,c_time,policy_num,num_id,id,career_type,career_work,pro_id,status,pay_type,pay_url')->order('id desc')->select();
            foreach($result as $key => $val){
                $s = strtotime($val['s_time']);
                if($s < $today){
                    $result[$key]['status'] = 6;
                    $result[$key]['is_add'] = 1;
                }else{
                    $result[$key]['status'] = 5;
                    $result[$key]['is_add'] = 0;
                }
            }
        }elseif($data['type'] == 2){
            $where = [
                'uid' => $data['uid'],
                'status' => 1
            ];
            $result = Db::name('order')->where($where)->field('policy_money,applicant_name,s_time,e_time,c_time,policy_num,num_id,id,career_type,career_work,pro_id,status,policy_money,pay_type,pay_url')->order('id desc')->select();
        }elseif($data['type'] == 9){
            $where = [
                'uid' => $data['uid'],
                'status' => 1,
                'retention_step' => 1
            ];
            $resultRetention = Db::name('order_retention')->where($where)->order('id desc')->select();
            $result = $this->handleRetention($resultRetention);
        }elseif($data['type'] == 3){
            $where = [
                'uid' => $data['uid'],
                'status' => 6,
                's_time' => ['elt', date("Y-m-d",strtotime("-1 day")) . ' 23:59:59'],
                'e_time' => ['gt', datetime(time(), 'Y-m-d') . ' 23:59:59'],
            ];
            $orders = Db::name('order')->where($where)->field('policy_money,applicant_name,s_time,e_time,c_time,policy_num,num_id,id,career_type,career_work,pro_id,status,pay_type,pay_url')->order('id desc')->select();
            foreach($orders as $key => $val){
                $s = strtotime($val['s_time']);
                $e = strtotime($val['e_time']);
                $thirty = strtotime('+30 day');
                $diff = ($e + 1 - $s)/86400;
                if(($e < $thirty) && ($diff > 30)){
                    $result[$key] = $val;
                }
            }
        }elseif($data['type'] == 4){
            $where = [
                'uid' => $data['uid'],
                'status' => ['in', [6,7]],
                'e_time' => ['lt', datetime(time(), 'Y-m-d')],
            ];
            $result = Db::name('order')->where($where)->field('policy_money,applicant_name,s_time,e_time,c_time,policy_num,num_id,id,career_type,career_work,pro_id,status,pay_type,pay_url')->order('id desc')->select();
        }elseif ($data['type'] == 5){
            $where = [
                'uid' => $data['uid'],
                'status' => 5,
                's_time' => ['gt', datetime(time(), 'Y-m-d') . ' 23:59:59'],
            ];
            $result = Db::name('order')->where($where)->field('policy_money,applicant_name,s_time,e_time,c_time,policy_num,num_id,id,career_type,career_work,pro_id,status,pay_type,pay_url')->order('id desc')->select();
        }elseif ($data['type'] == 8){
            $where = [
                'uid' => $data['uid'],
                'status' => 8,
            ];
            $result = Db::name('order')->where($where)->field('policy_money,applicant_name,s_time,e_time,c_time,policy_num,num_id,id,career_type,career_work,pro_id,status,pay_type,pay_url')->order('id desc')->select();
        }else{
            $where = [
                'uid' => $data['uid'],
                'status' => ['in', [1, 2, 5, 6, 8]]
            ];
            $result = Db::name('order')->where($where)->field('policy_money,applicant_name,s_time,e_time,c_time,policy_num,num_id,id,career_type,career_work,pro_id,status,pay_type,pay_url')->order('id desc')->select();
            
            $where2 = [
                'uid' => $data['uid'],
                'status' => 1,
                'retention_step' => 1
            ];
            $resultRetention = Db::name('order_retention')->where($where2)->order('id desc')->select();
            $result2 = $this->handleRetention($resultRetention);
        }

        $company = config('companys.list');

        if($data['type'] != 9){
            foreach($result as $key => $val){
                $result[$key]['name'] = $this->getNames($val['num_id']);
                $result[$key]['title'] = $this->getTitle($val);
                $result[$key]['type'] = $data['type'];

                $pro_Other = Db::name('product_other')->where(['pro_id' => $val['pro_id']])->field('company_name,company_bank_no,company_bank_name,company_username')->find();

                $result[$key]['other'] = $pro_Other;

                $result[$key]['pay_type'] = empty($val['pay_url']) ? ($val['pay_type'] == 1 ? 1 : 4) : 0;//0 线上   1  线下   4 两种方式都支持

                if (empty($data['type']))
                {
                    $stime = strtotime($val['s_time']);
                    $etime = strtotime($val['e_time']);
                    switch ($val['status'])
                    {
                        case 1:
                            $result[$key]['type'] = 2;
                            break;
                        case 5:
                            if (strtotime($val['s_time']) > time())
                            {
                                $result[$key]['type'] = 5;
                            }else{
                                $result[$key]['type'] = 1;
                            }
                            break;
                        case 6:
                            if (strtotime($val['e_time']) < time())
                            {
                                $result[$key]['type'] = 4;
                            }else{
                                $result[$key]['type'] = 1;
                            }
                            break;
                        case 8:
                            $result[$key]['type'] = 8;
                            break;
                        case 2:
                            $result[$key]['type'] = 5;
                            break;
                    }
                }
                
                $companyId = Db::name('product')->where(['id' => $val['pro_id']])->value('company_id');
                $result[$key]['company_name'] = '中国平安';//$company[$companyId];
                $result[$key]['career_type_name'] = Db::name('career_type')->where(['id' => $val['career_type']])->value('name');
                $result[$key]['career_work_name'] = Db::name('career_work')->where(['id' => $val['career_work']])->value('name');
            }
        }
        if(empty($data['type'])){
            $result = array_merge($result,$result2);
        }
        
        return $result;
    }
    
    /**
     * 数据处理
     */
    public function handleRetention($data)
    {
        $return = array();
        $result = array();
        
        $company = config('companys.list');
        foreach($data as $key => $val){
            
            $vv = json_decode($val['retention_info'], true);
            $v2 = json_decode($vv, true);
            
            $return[$key]['applicant_name'] = $v2['com_name'];
            //$product = Db::name('product')->where(array('pro_num'=>$v2['pro_num']))->field('company_id')->find();

            if (isset($v2['work_id']))
            {
                $career = Db::name('career_work')->where(array('id'=>$v2['work_id']))->field('name')->find();
            }else{
                $career['name'] = '';
            }
            
            $return[$key]['type'] = $val['retention_code'];
            $return[$key]['company_name'] = '中国平安';//$company[$product['company_id']];
            $return[$key]['career_type_name'] = $career['name'];
            $return[$key]['c_time'] = $val['c_time'];
            $return[$key]['type'] = '9';
            $return[$key]['retention_code'] = $val['retention_code'];
            $return[$key]['num_id'] = '';
            $return[$key]['policy_num'] = '';
        }
        
        return $return;
    }
    
    
    /**
     * 取消支付功能
     * num_id:订单id
     * 'status' => 8,
     */
    public function noPay($data)
    {
        $where = [
            'num_id' => $data['num_id'],
        ];
        $order = [
            'status' => 8
        ];
        $record = [
            'status' => 3
        ];
        try {
            Db::startTrans();
            $re1 = Db::name('order')->where($where)->update($order);
            $re2 = Db::name('employee_info_record')->where($where)->update($record);
            if($re1 && $re2){
                $result = 200;
                Db::commit();
            }else{
                $result = 100;
                Db::rollback();
            }
        } catch (\Exception $e) {
            Db::rollback();
        }
        return $result;
    }
    
    
    /**
     * 获得被保人名字
     */
    public function getNames($num_id)
    {
        $names = array();
        $name = Db::name('employee_info_record')->where(array('num_id'=>$num_id))->field('name')->select();
        foreach($name as $v){
            $names[] = $v['name'];
        }
        return implode(',', $names);
    }
    
    /**
     * 获得保险标题
     */
    public function getTitle($data)
    {
        $where['career_type_id'] = isset($data['career_type']) ? $data['career_type'] : 0;
        $where['career_work_id'] = isset($data['career_work']) ? $data['career_work'] : 0;
        $where['product_id'] = isset($data['pro_id']) ? $data['pro_id'] : 0;
        $work = Db::name('type_work')->where($where)->field('title')->find();
        if($work){
            return $work['title'];
        }else{
            $product = Db::name('product')->where(array('id'=>$where['product_id']))->field('name')->find();
            return $product['name'];
        }
    }
    
    /**
     * 获得订单详情
     * order_id 订单表id
     */
    public function getOrderDetail($data)
    {
        $where['o.num_id'] = $data['num_id'];
        $order = Db::name('order o')
            ->join('order_applicant op', 'o.num_id=op.num_id', 'left')
            ->join('product pro', 'o.pro_id=pro.id', 'left')
            ->field('o.id, o.num_id, o.pay_money, o.bill_url, o.policy_url, o.policy_num, o.c_time, o.program_id, o.pro_id,
                o.s_time, o.e_time, op.com_name, op.credit_code, op.contact_addr, o.career_type, o.career_work, pro.company_id,
                pro.clause, pro.clause_name, pro.cate_id, pro.claims_guidelines')
            ->where($where)
            ->find();

        //处理保险条例            
        $clause = explode(',', $order['clause']);
        $clause_name = explode(',', $order['clause_name']);
        $clause_name = isset($clause_name[1]) ? $clause_name : explode('，', $order['clause_name']);
        foreach($clause as $k => $v){
            $clauseArr[$k]['name'] = $clause_name[$k];
            $clauseArr[$k]['url'] = $v;
        }
        
        //分享图片
        if($order['cate_id'] == 2){
            $order['share'] = '/uploads/gzimg.jpg';
        }elseif($order['cate_id'] == 6){
            $order['share'] = '/uploads/xpimg.jpg';
            $order['record'] = Db::name('employee_info_record')->where(array('num_id'=>$data['num_id']))->field('id, name, paper_num, s_time, e_time')->find();
        }

        //计算投保月数
        $monthTotal = BaseServices::getInstance()->getMonth($order['s_time'], $order['e_time']);
        //获取产品批改配置
        $proCorrectConfig = Db::name('product_correct_rate')
            ->where([
                'pro_id' => ['eq', $order['pro_id']]
            ])
            ->column('is_add, is_change', 'month');
        
        //判断是否可以添加
        $s = strtotime($order['s_time']);
        $today = time();
        $order['is_add'] = ($proCorrectConfig[$monthTotal['month']]['is_add'] == 1 && $s < $today) ? 1 : 0;
        $order['is_change'] = ($proCorrectConfig[$monthTotal['month']]['is_change'] == 1 && $s < $today) ? 1 : 0;//$monthTotal['month'] > 6 &&
        
        $order['clause'] = $clauseArr;
        $order['title'] = $this->getTitle($order);
        $order['company_id'] = isset($order['company_id']) ? $order['company_id'] : 12;
        $order['company'] = '中国平安';//config('companys.list')[$order['company_id']];
        return $order;
    }
    
    /**
     * 获得被保险人信息
     * type=1 保障中(状态是2的数据)
     * type=2 待起保(状态是1、2、4的数据)
     * num_id 订单编号
     * program_id 方案id
     */
    public function getAssuredName($data)
    {
        $today = time();
        $result = array();
        
        //保单保额获取
        $prowhere['id'] = $data['program_id'];
        $program = Db::name('product_program')->where($prowhere)->find();
        $safeguard = \GuzzleHttp\json_decode($program['safeguard'], true);
        $money = intval($safeguard[0]['money']);
        
        if($data['type'] == 1){
            $where = [
                'num_id' => $data['num_id'],
                'status' => 2,
                'is_insured' => 1,
                's_time' => ['elt', datetime(time(), 'Y-m-d') . ' 00:00:00'],
                'e_time' => ['gt', datetime(time(), 'Y-m-d') . ' 00:00:00'],
            ];
        }else{
            $where = [
                'num_id' => $data['num_id'],
                'status' => ['in', [1, 2, 4]],
                's_time' => ['gt', datetime(time(), 'Y-m-d') . ' 23:59:59'],
            ];
        }
        $names = Db::name('employee_info_record')
            ->field('name,paper_num,s_time,e_time,status')
            ->where($where)
            ->select();
        foreach($names as $key => $val){
            $names[$key]['insured'] = $money;
        }
        
        return $names;
    }
    
    /**
     * 添加人员页面
     */
    public function enterClaims($data)
    {
        $order = Db::name('order o')
            ->join('product_other p', 'o.pro_id=p.pro_id')
            ->where(array('o.num_id' => $data['num_id']))
            ->field('p.min_age,p.max_age,o.pro_id')
            ->find();
        $chooseDateConfig = ProductLogic::getDisabledChooseStartDate($order['pro_id'], 'correction_date');
            
        $order['min_date'] = $chooseDateConfig['min_date'];
        return $order;
    }
    
    /**
     * pro_id 产品id
     * num_id订单编号
     * name雇员姓名
     * paper_num身份证号
     * paper_type 1 身份证
     * status 1 （t_employee_info_record 未审核，t_order_assured 批增）
     * type 1 批增（t_employee_info_record）
     * t_policy_info_change 暂时未定是否往这个表添加数据
     * 100:添加失败；200：成功；300：不允许添加保障人员；400：年龄不符;500
     */
    public function addEmployee($data)
    {
        $rate = Db::name('product_correct_rate')->where(array('pro_id' => $data['pro_id']))->field('is_add')->find();
        $identity = new \fast\Identity();
        if($rate['is_add'] == 1){
            $start_time = $data['min_date'].' 00:00:00';
            //获得uid
            $order = Db::name('order o')
                ->join('product_other p', 'o.pro_id=p.pro_id')
                ->join('product pro', 'o.pro_id=pro.id')
                ->where(array('o.num_id' => $data['num_id']))
                ->field('o.uid,o.pay_type,o.s_time,o.e_time,o.career_work,o.applicant_name,o.protect_num,o.policy_num,
                    p.min_age,p.max_age,pro.name,pro.id as pro_id,pro.type,pro.status,pro.company_id,pro.pro_num')
                ->find();
            $job_name = Db::name('career_work')->where(['id' => $order['career_work']])->value('name');
            
            //人数转化为数组
            $people = \GuzzleHttp\json_decode($data['people'], true);
            $money = Db::name('order o')
                ->join('product_program p', 'o.program_id=p.id', 'left')
                ->where(array('o.num_id' => $data['num_id']))
                ->field('p.year_money')
                ->find();

            $check_rate = Db::table('t_product_correct_rate')->where(['pro_id' => $order['pro_id'], 'status' => '1'])->column('rate, is_add, is_change, correction_rate_form, correction_rate', 'month');

            //计算投保单剩余月数或者天数得出增加人员的保费
            $monthTotal = BaseServices::getInstance()->getMonth($order['s_time'], $order['e_time']);
            $monthTotal['month'] = $monthTotal['month'] - intval((time() - strtotime($order['s_time']))/3600/24/30);

            $monthTotal['month'] = $monthTotal['month'] <= 0 ? 1 : ($monthTotal['month'] >= 12 ? 12 : $monthTotal['month']);

            $check_rate[$monthTotal['month']]['correction_rate'] = $check_rate[$monthTotal['month']]['correction_rate'] <= 0 ? $check_rate[$monthTotal['month']]['rate'] : $check_rate[$monthTotal['month']]['correction_rate'];

            $money['year_money'] = empty($check_rate[$monthTotal['month']]['correction_rate_form']) ? $money['year_money'] * $check_rate[$monthTotal['month']]['correction_rate'] / 100 : $money['year_money'] / 365 * $check_rate[$monthTotal['month']]['correction_rate'] / 100 * $monthTotal['day'];

            $totleMoney = $money['year_money'] * (count($people));
                
            $policy = [
                'num_id' => $data['num_id'],
                'uid' => $order['uid'],
                'pay_type' => $order['pay_type'],
                'check_inc' => count($people),
                'check_status' => 3,
                'c_time' => datetime(time(), 'Y-m-d H:i:s'),
                's_time' => $start_time,
                'e_time' => $order['e_time'],
                'money' => $totleMoney
            ];
            
            Db::startTrans();
            $change = Db::name('policy_info_change')->insert($policy);
            $changeId = Db::name('policy_info_change')->getLastInsID();
            $insert = array();
            $addData = array();
            $changeData = array();
            foreach($people as $val){
                    
                /**
                  * 检查该身份证人员是否存在
                  * @var array $where
                */
                $where = [
                    'uid' => $order['uid'],
                    'num_id' => $data['num_id'],
                    'paper_num' => $val['identity'],
                    'e_time' => ['egt', datetime(time(), 'Y-m-d H:i:s')],
                    'is_insured' => 1
                ];
                $has = Db::name('employee_info_record')->where($where)->find();
                if($has){
                    Db::rollback();
                    return ['code'=>100, 'msg'=>$val['name'].'该用户已在保'];
                }
                
                /**
                 * 检查该身份证人员是否存在
                 * @var array $where
                 */
                /*$where = [
                    'uid' => $order['uid'],
                    'num_id' => $data['num_id'],
                    'paper_num' => $val['identity'],
                    'status' => ['neq', 5],
                    'is_insured' => 0
                ];
                $has = Db::name('employee_info_record')->where($where)->find();
                if($has){
                    Db::rollback();
                    return ['code'=>100, 'msg'=>$val['name'].'该用户已添加，还未支付'];
                }*/
                    
                /**
                  * 判断年龄是否符合
                  * @var Ambiguous $age
                */
                $age = $identity->getAge($val['identity']);
                if(($order['min_age'] > $age) || ($order['max_age'] < $age)){
                    Db::rollback();
                    return ['code'=>100, 'msg'=>$val['name'].'该用户年龄不在保障范围'];
                }
                    
                $arr['change_info_id'] = $changeId;
                $arr['employee_code'] = '';
                $arr['num_id'] = $data['num_id'];
                $arr['uid'] = $order['uid'];
                $arr['c_time'] = datetime(time(), 'Y-m-d H:i:s');
                $arr['s_time'] = $start_time;
                $arr['e_time'] = $order['e_time'];
                $arr['name'] = $val['name'];
                $arr['sex'] = $identity->getSex($val['identity']);
                $arr['age'] = $age;
                $arr['paper_type'] = 1;
                $arr['paper_num'] = $val['identity'];
                $arr['job_name'] = $job_name;
                $arr['status'] = 4;
                $arr['money'] = $money['year_money'];
                $arr['type'] = 1;
                $arr['change_id'] = 0;
                $insert[] = $arr;
                $arr['flag'] = '新增';
                $arr['operate_status'] = 'A';
                $addData[] = $arr;
                unset($arr['num'], $arr['flag']);
                $changeData[] = $arr;
                unset($arr['operate_status']);
            }
            
            $check = $this->check($order, $data, $totleMoney, $changeId, $changeData, $insert, false, count($data['people']));

            $saleAdmin = new SaleAdmin();
            $saleAdmin->retailStore([
                'num_id' => $data['num_id'],
                'change_id' => $changeId,
                'uid' => Db::name('user')->where(['id' => $order['uid']])->value('pid'),
                'pro_id' => $order['pro_id'],
                'policy_money' => $totleMoney
            ]);

            if($check['code'] == 200){
                //1 注册积分   2 分享积分    3 消费积分    4 赠送积分
                $params = [
                    'uid' => $order['uid'],
                    'integralType' => 3,
                    'policyMoney' => $totleMoney,
                    'sTime' => $policy['s_time'],
                    'oddNumbers' => $policy['num_id'].'_'.$changeId
                ];
                Integral::getInstance()->setUserIntegral($params);

                $result['code'] = 200;
                $result['data']['num_id'] = $data['num_id'].'_'.$changeId;   //policy_info_change表id
                $result['data']['money'] = $money['year_money'] * (count($people));
            }else{
                $result['code'] = $check['code'];
                $result['msg'] = $check['msg'];
            }
            Db::commit();
            return $result;
        }else{
            Db::commit();
            return ['code'=>100, 'msg'=>'该产品不允许添加客户'];
        }
    }
    
    
    /**
     * 获得在保人员信息
     * num_id：订单id
     */
    public function getOriginal($data)
    {
        $where = [
            'num_id' => $data['num_id'],
            'is_insured' => 1,
            'status' => 2
        ];
        $people = Db::name('employee_info_record')->where($where)->field('id, name, paper_num, s_time, e_time')->select();
        $today = time();
        $result = array();
        
        foreach($people as $key => $val){
            $s = strtotime($val['s_time']);
            $e = strtotime($val['e_time']);
            $diff = ($e + 1 - $s)/86400;
            
            if(($s < $today) && ($e > $today)){
//                 if(($s < $today) && ($e > $today) && ($diff > 31)){
                $result[$key] = $val;
            }
        }
        
        return $result;
    }
    
    /**
     * 理赔接口
     * 获得保障期限、保障人员
     * num_id 订单编号
     */
    public function getClaims($data)
    {
        $order = Db::name('order')->where(array('num_id'=>$data['num_id']))->field('s_time, e_time')->find();
        
        
        $where = [
            'num_id' => $data['num_id'],
            'status' => 2,
            'is_insured' => 1,
            's_time' => ['elt', datetime(time(), 'Y-m-d') . ' 00:00:00']
        ];
        $names = Db::name('employee_info_record')->where($where)->field('id,name,paper_num')->select();
        
        if($order['e_time'] >= date('Y-m-d')){
            $order['e_time'] = date('Y-m-d');
        }else{
            $order['e_time'] = date('Y-m-d', strtotime($order['e_time']));
        }
        $order['s_time'] = date('Y-m-d', strtotime($order['s_time']));
        
        $reason = config('reason.list');
        $do = [];
        foreach ($reason as $key => $item) {
            $do[] = ['name' => $item, 'value' => $key, 'state' => false];
        }
        return [
            'date' => $order,
            'names' => $names,
            'reason' => $do
        ];
    }
    
    /**
     * 报案理赔接口
     */
    public function addClaims($data)
    {
        //获取订单信息
        $order = Db::name('order o')
            ->join('product p', 'o.pro_id=p.id', 'left')
            ->where(array('o.num_id'=>$data['num_id']))
            ->field('o.uid,o.pro_id,p.name,p.company_id')
            ->find();
         
        $add = [
            'happen_time' => $data['happen_time'],
            'contact_phone' => $data['phone'],
            'risk_desc' => $data['risk_desc'],
            'claim_sn' => "cn-" . $this->get_order_num(),
            'create_time' => date("Y-m-d H:i:s"),
            'update_time' => date("Y-m-d H:i:s"),
            'idcard_num' => $data['paper_num'],
            'assured' => $data['name'],
            'claim_status' => ClaimOrder::REPORTED,
            'pro_name' => $order['name'],
            'com_name' => '中国平安',//config('companys.list')[$order['company_id']],
            'pro_id' => $order['pro_id'],
            'uid' => $order['uid'],
            'num_id' => $data['num_id']
        ];
        
        $where = [
            'num_id' => $data['num_id'],
            'idcard_num' => $data['paper_num'],
            'claim_status' => ['neq', 4]
        ];
        $has = Db::name('claim_order')->where($where)->find();
        if($has){
           return  300;
        }
        
        $list = Db::name('claim_order')->insert($add);
        return $list ? 200 : 100;
    }
    
    
    /**
     *  生成订单编号
     * author yangbin
     */
    public function get_order_num()
    {
//         return date("ymd", time()) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return date("Ymdh", time()) . substr(microtime(), 2, 3);
    }
    
    /**
     * 保障人员替换接口
     * num_id
     */
    public function changeEmployee($data)
    {
        $old = json_decode($data['old'],true);
        $new = json_decode($data['new'],true);
        
        //获得订单及相应数据
        $order = Db::name('order o')
            ->join('product_program p', 'o.program_id=p.id', 'left')
            ->join('product_other po', 'o.pro_id=po.pro_id', 'left')
            ->where(array('o.num_id' => $data['num_id']))
            ->field('o.uid,o.pay_type,o.e_time,o.career_work,o.applicant_name,o.protect_num,o.policy_num,
                p.year_money,o.num_id,po.min_age,po.max_age')
            ->find();
        $job_name = Db::name('career_work')->where(['id' => $order['career_work']])->value('name');
        $identity = new \fast\Identity();
//         $money = Db::name('order o')
//             ->join('product_program p', 'o.program_id=p.id', 'left')
//             ->where(array('o.num_id' => $data['num_id']))
//             ->field('p.year_money')
//             ->find();
        
        //添加数据到policy_info_change(批改信息表)表
        $policy = [
            'num_id' => $order['num_id'],
            'uid' => $order['uid'],
            'check_inc' => count($old),
            'check_dec' => count($old),
            'money' => 0,
            'pay_money' => 0,
            'check_status' => 0,
            'c_time' => date("Y-m-d H:i:s"),
            's_time' => $data['min_date'].' 00:00:00',
            'e_time' => $order['e_time'],
        ];
        
        Db::startTrans();
        $policyData = Db::name('policy_info_change')->insert($policy);
        $policyId = Db::name('policy_info_change')->getLastInsID();
            
        //保障人员替换
        foreach($old as $key => $val){
                    
                //判断年龄是否符合投保范围
            $age = $identity->getAge($new[$key]['identity']);
            if(($order['min_age'] > $age) || ($order['max_age'] < $age)){
                Db::rollback();
                return ['code'=>100, 'msg'=>'该客户年龄不在投保年龄范围'];
            }
                
                //判断原用户是否已被替换
            $where = [
                'num_id' => $order['num_id'],
                'change_id' => $val['id'],
            ];
            $has = Db::name('employee_info_record')->where($where)->find();
            if($has){
                Db::rollback();
                return ['code'=>100, 'msg'=>$val['name'].'客户没有找到原值，请核实后重新操作'];
            }
                
                //替换者是否已加入
            $where2 = [
                'num_id' => $order['num_id'],
                'paper_num' => $new[$key]['identity'],
                'e_time' => ['egt', datetime(time(), 'Y-m-d H:i:s')],
                'is_insured' => ['eq', 1],
            ];
            $has2 = Db::name('employee_info_record')->where($where2)->find();
            if($has2){
                Db::rollback();
                return ['code'=>100, 'msg'=>$new[$key]['name'].'客户已在保'];
            }
            
            //获得被替换着保费金额
            $oldMoney = Db::name('employee_info_record')->where(array('id'=>$val['id']))->field('money')->find();
            
            $arr['change_info_id'] = $policyId;
            $arr['employee_code'] = '';
            $arr['num_id'] = $data['num_id'];
            $arr['uid'] = $order['uid'];
            $arr['c_time'] = datetime(time(), 'Y-m-d H:i:s');
            $arr['s_time'] = $data['min_date'].' 00:00:00';
            $arr['e_time'] = $order['e_time'];
            $arr['name'] = $new[$key]['name'];
            $arr['sex'] = $identity->getSex($new[$key]['identity']);
            $arr['age'] = $identity->getAge($new[$key]['identity']);
            $arr['paper_type'] = 1;
            $arr['paper_num'] = $new[$key]['identity'];
            $arr['job_name'] = $job_name;
            $arr['status'] = 4;
            $arr['money'] = $oldMoney['money'];
            $arr['type'] = 1;
            $arr['change_id'] = $val['id'];
            $dat[] = $arr;
            $arr['flag'] = '新增';
            $arr['operate_status'] = 'A';
            $addData[] = $arr;
            unset($arr['num'], $arr['flag']);
            $arr['operate_status'] = 'C';
            $arr['old_name'] = $val['name'];
            $arr['old_paper_num'] = $val['paper_num'];
            $arr['operate_status'] = 'C';
            $changeData[] = $arr;
            unset($arr['operate_status'],$arr['old_name'],$arr['old_paper_num']);
        }
        
        $return = $this->check($order, $data, 0, $policyId, $changeData, $dat, true, count($old));
        Db::commit();
        return $return;
    }
    
    /**
     * 替换人员处理
     * ($order, $data, $totleMoney, $changeId, $changeData, false);
     */
    public function check($order, $data, $totleMoney, $changeId, $changeData, $dat, $is_replace, $numPeople)
    {
        $file = './error_log.txt';
        //线下批改只需要审核时请求批改接口
        $work = Db::name('career_work')->where(['id' => $order['career_work']])->field('name,type')->find();
        $params = [
            'pay_type' => $order['pay_type'],
            'money' => $totleMoney,
            's_time' => $data['min_date'] . ' 00:00:00',
            'employerList' => $changeData,
            'policy_num' => $order['policy_num'],
            'num_id' => $data['num_id'],
            'work_type' => $work['type'],
            'work_name' => $work['name'],
            'applicant_name' => $order['applicant_name'],
            'protect_num' => $order['protect_num'],
            'change_id' => $changeId,
            'add_count' => $numPeople
        ];
        //批改
        $change_info = Db::table('t_policy_info_change')->where(['id' => $changeId])->field('change_num,ext_info')->find();//批单申请号
        
        Db::startTrans();
        if (!$change_info['change_num']) {
            $res = ShenZhenPingAnEmployerLogic::getInstance()->correct($params);
            
            //添加日志
            log_put($res, '订单提交保险公司-correct()，返回数据');

            if (!$res['code']) {
                Db::rollback();
                Db::name('policy_info_change')->where(array('id'=>$changeId))->delete();
                return array('code'=>100, 'msg'=>$res['msg']);
            }
            $res = $res['data'];
            Db::table('t_employee_info_record')->insertAll($dat);
        } else {
            $res = json_decode($change_info['ext_info'], true);
        }
        
        if (in_array($order['pay_type'], [0,4])) {//平安雇主线上批改
            if (!$is_replace) {
                $res['change_id'] = $changeId;
                $res = ShenZhenPingAnEmployerLogic::getInstance()->correctPay($res);
                
                //添加日志
                log_put($res, '订单提交保险公司-correctPay()，返回数据');
                
                if (!$res['code']) {
                    Db::rollback();
                    Db::name('policy_info_change')->where(array('id'=>$changeId))->delete();
                    return array('code' => 100, 'msg'=>$res['msg']);
                }
            }
        } else {
            Db::table('t_policy_info_change')->where(['id' => $changeId])->update(['ext_info' => json_encode($params)]);
        }
        
        if (!$is_replace) { //增加人员需要跳转支付
            Db::commit();
            return array('code'=>200, 'msg'=>'数据提交成功');
        } else {
            //只有替换不需要审核
            $wh = ['num_id' => $data['num_id'], 'change_info_id' => $changeId];
            Db::table('t_employee_info_record')
                ->where($wh)
                ->update(['u_time' => datetime(time()), 'status' => 2, 'is_insured' => 1]);
            Db::table('t_policy_info_change')->where(['id' => $changeId])->update(['check_status' => 1, 'u_time' => datetime(time())]);
            
            //被替换者到期时间更改
            $up_e_time = date('Y-m-d H:i:s', strtotime($data['min_date']) - 1);
            foreach($dat as $key){
                Db::table('t_employee_info_record')
                    ->where(array('id'=>$key['change_id']))
                    ->update(['u_time' => datetime(time()), 'e_time' => $up_e_time,]);
            }
            
            Db::commit();
            return array('code'=>200, 'msg'=>'数据提交成功');
        }
    }
}

